/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dp1.titandevelop.titano.view.almac;

import dp1.titandevelop.titano.bean.Mensajes;
import dp1.titandevelop.titano.persistent.Empleado;
import dp1.titandevelop.titano.persistent.Kardex;
import dp1.titandevelop.titano.service.EmpleadoService;
import dp1.titandevelop.titano.service.KardexService;
import dp1.titandevelop.titano.service.ValidacionService;
import java.awt.Dimension;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.swing.JComboBox;
import javax.swing.JOptionPane;
import javax.swing.table.AbstractTableModel;

/**
 *
 * @author Yulian
 */
public class ModulosT_ALM_ActividadesPen extends javax.swing.JInternalFrame {
   
    private List<Date> listaFechas;
    private List<Integer> listaDocs;
    private List<Integer> listaTMs;
    
    private List<Empleado> listaEmp;
    private Mensajes sms = new Mensajes();
    
    private void addList (){
        for(int i=0;i<listaEmp.size();i++){
            this.cboxResponsable.addItem(listaEmp.get(i).getNombres() +" "+ listaEmp.get(i).getApellidop());
        }        
    }
    public void RefreshTable() {
        AbstractTableModel aux = (AbstractTableModel)tblResultados.getModel();
        aux.fireTableDataChanged();
    }
    public void habilitaBotones(){
        this.btnAceptar.setEnabled(true);
        this.btnDetalle.setEnabled(true);
    }
    private void inhabilitaBotones(){
        this.btnAceptar.setEnabled(false);
        this.btnDetalle.setEnabled(false);
    }
    public ModulosT_ALM_ActividadesPen() {
        initComponents();
        
        KardexService serv = new KardexService();
        EmpleadoService servEmp = new EmpleadoService();
        
        this.inhabilitaBotones();
        listaDocs = serv.buscarDocsPendientes();
        listaTMs = serv.buscarTiposMPendientes();
        listaFechas = new ArrayList<Date>();
        
        for(int i=0;i<listaDocs.size();i++){
            Date f = serv.buscarFechaDoc(listaDocs.get(i));
            listaFechas.add(f);
        }
        listaEmp = servEmp.buscar();
        tblResultados.setModel(modeloTabla);
        
        addList();
    }
    
    private AbstractTableModel modeloTabla = new AbstractTableModel()  {  
        
        @Override
        public int getRowCount() {
            return listaDocs.size(); // cuantos registros (filas)
        }      
        
        @Override
        public int getColumnCount() {
            return 4; // cuantas columnas
        }  
        
        String [] titles = {"Área","Movimiento","Doc.Relacionado","Fecha"};
        
        @Override
        public String getColumnName(int col){
            return titles[col];
        }        
          
        @Override
        public Object getValueAt(int rowIndex, int columnIndex) {
            Object res=null;      
            KardexService servK= new KardexService();
            List<Kardex> movs = servK.buscarPorDoc(listaDocs.get(rowIndex),listaTMs.get(rowIndex));
            int tipo = servK.reconoceProc(movs);
            DateFormat fecha = DateFormat.getDateInstance(DateFormat.MEDIUM);
            switch(columnIndex){
                case 0: if(tipo == 1) res = "Compras"; else if (tipo == 2) res = "Ventas"; else res = "Producción"; break;
                case 1: res = movs.get(0).getToTipoMovimiento().getDescripcion();break;
                case 2: res = listaDocs.get(rowIndex);break;
                case 3: res = fecha.format(listaFechas.get(rowIndex));break;
            }
            return res;
        }  
    };

    public int cboxIndex(JComboBox cbox){
        return cbox.getSelectedIndex()-1;
    }
    public boolean cboxVacio(JComboBox cbox){
        int index=cbox.getSelectedIndex()-1;
        if(index==-1)
            return true;
        else
            return false;
    }
  
    
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel6 = new javax.swing.JLabel();
        cboxResponsable = new javax.swing.JComboBox();
        btnAceptar = new javax.swing.JButton();
        btnSalir = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblResultados = new javax.swing.JTable();
        btnDetalle = new javax.swing.JButton();

        setResizable(true);
        setTitle("Actividades Pendientes");
        setToolTipText("");

        jLabel6.setText("Responsable");

        cboxResponsable.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Seleccionar" }));

        btnAceptar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/asignar.png"))); // NOI18N
        btnAceptar.setToolTipText("Aceptar");
        btnAceptar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAceptarActionPerformed(evt);
            }
        });

        btnSalir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/retroceder.png"))); // NOI18N
        btnSalir.setToolTipText("Salir");
        btnSalir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSalirActionPerformed(evt);
            }
        });

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Lista de Pendientes"));

        tblResultados.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Área", "Movimiento", "Producto Relacionado", "Fecha"
            }
        ));
        tblResultados.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tblResultadosMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tblResultados);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 567, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 235, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(8, 8, 8))
        );

        btnDetalle.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/detalle.png"))); // NOI18N
        btnDetalle.setToolTipText("Detalle");
        btnDetalle.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDetalleActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(8, 8, 8)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(10, 10, 10)
                        .addComponent(jLabel6)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(cboxResponsable, javax.swing.GroupLayout.PREFERRED_SIZE, 159, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(btnDetalle)
                        .addGap(0, 0, 0)
                        .addComponent(btnAceptar)
                        .addGap(0, 0, 0)
                        .addComponent(btnSalir)))
                .addGap(8, 8, 8))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addGap(8, 8, 8)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(8, 8, 8)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(btnSalir)
                            .addComponent(btnAceptar)
                            .addComponent(btnDetalle)))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(18, 18, 18)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel6)
                            .addComponent(cboxResponsable, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnAceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAceptarActionPerformed
ValidacionService val = new ValidacionService();

        int indexEmp = cboxIndex(cboxResponsable), idEmp;
        
        
        if(!val.esCBoxVacio(cboxResponsable)){
            try{

                KardexService serv = new KardexService();

                idEmp=listaEmp.get(indexEmp).getIdempleado();
                int index= tblResultados.getSelectedRow();
                
                if(serv.aceptaSolicitud(this.listaDocs.get(index),this.listaTMs.get(index),idEmp)){
                    this.listaDocs.remove(index);
                    this.listaFechas.remove(index);                
                }
                else{
                    JOptionPane.showInternalMessageDialog(this.getRootPane(),"La solicitud sigue pendiente.\nUno o más movimientos relacionados no pueden realizarse.\n Ver detalle de solicitud","Aviso",JOptionPane.WARNING_MESSAGE);
                }
                
                this.inhabilitaBotones();
                this.RefreshTable();
                this.dispose();                

            } catch(Exception e) {

                JOptionPane.showInternalMessageDialog(this.getRootPane(),sms.getError(),"Error",JOptionPane.ERROR_MESSAGE);
            }
        }
        else{
            JOptionPane.showInternalMessageDialog(this.getRootPane(), "Debe ingresarse al responsable de la operación.","Aviso",JOptionPane.WARNING_MESSAGE);
        }
    }//GEN-LAST:event_btnAceptarActionPerformed

    private void btnSalirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSalirActionPerformed
        this.dispose();        // TODO add your handling code here:
    }//GEN-LAST:event_btnSalirActionPerformed

    private void tblResultadosMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tblResultadosMouseClicked
        if(evt.getClickCount()==1){
            this.habilitaBotones();
        }
    }//GEN-LAST:event_tblResultadosMouseClicked

    private void btnDetalleActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDetalleActionPerformed
       
        //Instancio la ventana
        int index =this.tblResultados.getSelectedRow() ;
        ModulosT_ALM_MovMatPendientes ventanaDetalle = new ModulosT_ALM_MovMatPendientes(listaDocs.get(index),listaTMs.get(index));
        this.getParent().add(ventanaDetalle);

        Dimension desktopSize = this.getParent().getSize();
        Dimension jInternalFrameSize = ventanaDetalle.getSize();
        ventanaDetalle.setLocation((desktopSize.width - jInternalFrameSize.width) / 2,(desktopSize.height - jInternalFrameSize.height)/4 );
        ventanaDetalle.show();

        //Inhabilito los botones una vez realizada la acción
        this.inhabilitaBotones();
    }//GEN-LAST:event_btnDetalleActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAceptar;
    private javax.swing.JButton btnDetalle;
    private javax.swing.JButton btnSalir;
    private javax.swing.JComboBox cboxResponsable;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tblResultados;
    // End of variables declaration//GEN-END:variables
}
